<template>
    <div>
        <el-form :ref="formRef" :model="formData" :rules="rules" label-width="auto">
            <el-form-item label="保全类型" label-width="auto" :rules="rules.trial_extra_type" :prop="`trial_extra_type`">
                <el-select v-model="formData.trial_extra_type" placeholder="请选择保全类型" >
                    <el-option label="初次" value="初次"></el-option>
                    <el-option label="追加" value="追加"></el-option>
                    <el-option label="续保" value="续保"></el-option>
                    <el-option label="解除" value="解除"></el-option>
                </el-select>
            </el-form-item>

            <el-table id="dsr-list" class="mb2" :data="formData.dsr" :border="false" :show-header="false">

                <el-table-column>
                    <template slot-scope="scope">

                        <el-row style="font-weight: bold;font-size: 2rem">
                            {{ (scope.$index+1) +'.'+ scope.row.DW }}
                        </el-row>
                        <el-row>
                            <el-form-item label="当事人类型">
                                <el-radio-group v-model="scope.row.type">
                                    <el-radio :label="1">个人</el-radio>
                                    <el-radio :label="2">公司或组织机构</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-row>


                        <div v-if="scope.row.type === 1">

                            <el-form-item label="姓名" :rules="rules.XM" :prop="`dsr.`+ scope.$index+`.XM`">
                                <el-input v-model="scope.row.XM"></el-input>
                            </el-form-item>
                            <el-form-item label="身份证号码" :rules="rules.ZJHM" :prop="`dsr.`+scope.$index+`.ZJHM`">
                                <el-input v-model="scope.row.ZJHM" @input="parseZJHM(scope.row)"></el-input>
                            </el-form-item>

                            <el-form-item label="性别" :rules="rules.XB" :prop="`dsr.`+scope.$index+`.XB`">
                                <el-radio-group v-model="scope.row.XB">
                                    <el-radio label="男">男</el-radio>
                                    <el-radio label="女">女</el-radio>
                                </el-radio-group>
                            </el-form-item>

                            <el-form-item label="民族" :rules="rules.MZ" :prop="`dsr.`+scope.$index+`.MZ`">
                                <MZ v-model="scope.row.MZ"></MZ>
                            </el-form-item>


<!--                            <el-form-item label="出生日期" :rules="rules.CSRQ" :prop="`dsr.`+scope.$index+`.CSRQ`">-->
<!--                                <BirthdayPicker v-model="scope.row.CSRQ"-->
<!--                                                @change="(v)=>{ return onBirthdayChange(v,scope); }"></BirthdayPicker>-->
<!--                            </el-form-item>-->
                            <el-form-item label="出生日期" :rules="rules.CSRQ" :prop="`dsr.`+scope.$index+`.CSRQ`">
                                <el-date-picker
                                        v-model="scope.row.CSRQ"
                                        type="date"
                                        value-format="yyyy-MM-dd"
                                        placeholder="选择日期">
                                </el-date-picker>
                            </el-form-item>

                            <el-form-item label="联系电话" :rules="getDHValidator(scope.row)" :prop="`dsr.`+scope.$index+`.DH`">
                                <el-tag v-for="tag in scope.row.DH" closable :disable-transitions="false"
                                        @click="handleDHEdit(tag,scope.row)" @close="handleDHDel(tag,scope.row,scope)"
                                        :key="tag.trial_dsr_extra_id">
                                    {{tag.content}}
                                </el-tag>
                                <el-input :max-length="15" class="input-new-tag"
                                          v-if="scope.row.is_input_DH" v-model="scope.row.input_DH"
                                          :ref="'inputDH'+scope.row.trial_dsr_id" size="small"
                                          @keyup.enter.native="handleDHInput(scope.row,scope)"
                                          @blur="handleDHInput(scope.row,scope)"></el-input>
                                <el-button v-else class="button-new-tag" size="small"
                                           @click="showDHInput(scope.row,'inputDH'+scope.row.trial_dsr_id)">+ 新增
                                </el-button>
                            </el-form-item>

                            <el-form-item label="住址" :rules="rules.DZ" :prop="`dsr.`+scope.$index+`.DZ`">
                                <el-tag v-for="tag in scope.row.DZ" closable :disable-transitions="false"
                                        @click="handleDZEdit(tag,scope.row)" @close="handleDZDel(tag,scope.row,scope)"
                                        :key="tag.trial_dsr_extra_id">
                                    {{tag.content}}
                                </el-tag>
                                <el-input class="input-new-tag"
                                          v-if="scope.row.is_input_DZ" v-model="scope.row.input_DZ"
                                          :ref="'inputDZ'+scope.row.trial_dsr_id" size="small"
                                          @keyup.enter.native="handleDZInput(scope.row,scope)"
                                          @blur="handleDZInput(scope.row,scope)"></el-input>
                                <el-button v-else class="button-new-tag" size="small"
                                           @click="showDZInput(scope.row,'inputDZ'+scope.row.trial_dsr_id)">+ 新增
                                </el-button>
                            </el-form-item>
                        </div>

                        <div v-else>
                            <el-form-item label="公司或组织机构名称" :rules="rules.XM" :prop="`dsr.`+ scope.$index+`.XM`">
                                <el-input v-model="scope.row.XM"></el-input>
                            </el-form-item>
                            <el-form-item label="统一社会信用代码" :rules="{required:true,message:'统一社会信用代码',trigger:'blur'}"
                                          :prop="`dsr.`+scope.$index+`.ZJHM`">
                                <el-input v-model="scope.row.ZJHM"></el-input>
                            </el-form-item>

                            <el-form-item label="地址" :rules="rules.DZ" :prop="`dsr.`+scope.$index+`.DZ`">
                                <el-tag v-for="tag in scope.row.DZ" closable :disable-transitions="false"
                                        @click="handleDZEdit(tag,scope.row)" @close="handleDZDel(tag,scope.row,scope)"
                                        :key="tag.trial_dsr_extra_id">
                                    {{tag.content}}
                                </el-tag>
                                <el-input class="input-new-tag"
                                          v-if="scope.row.is_input_DZ" v-model="scope.row.input_DZ"
                                          :ref="'inputDZ'+scope.row.trial_dsr_id" size="small"
                                          @keyup.enter.native="handleDZInput(scope.row,scope)"
                                          @blur="handleDZInput(scope.row,scope)"></el-input>
                                <el-button v-if="scope.row.DZ.length === 0 && !scope.row.is_input_DZ"
                                           class="button-new-tag" size="small"
                                           @click="showDZInput(scope.row,'inputDZ'+scope.row.trial_dsr_id)">+ 新增
                                </el-button>
                            </el-form-item>
                        </div>

                        <el-row :gutter="20" class="mb2">
                            <el-col>
                                <el-button  type="primary" @click="onAddSSDLR(scope.row)">{{scope.row.SSDLR.length > 0? '继续添加' : '填写诉讼代理人'}}
                                </el-button>
                            </el-col>
                        </el-row>

                        <el-card class="box-card" v-for="(ssdlr,idx) in scope.row.SSDLR" :key="idx">
                            <div slot="header" class="clearfix">
                                <span>{{ parseInt(ssdlr.type) === 1? '律师':'个人' }}</span>

                                <el-button type="text" style="float: right;margin-right: 5px"
                                           @click="removeSSDLR(scope.row,idx)">删除
                                </el-button>

                                <el-button type="text" style="float: right;margin-right: 5px"
                                           @click="editSSDLR(ssdlr,scope.row,idx)">编辑
                                </el-button>
                            </div>
                            <div v-if="parseInt(ssdlr.type) === 1" class="text ">
                                <p>姓名：{{ ssdlr.XM }}</p>
                                <p>联系电话：{{ ssdlr.DH }}</p>
                                <p>事务所：{{ ssdlr.SWS }}</p>
                            </div>

                            <div v-else>
                                <p>姓名：{{ ssdlr.XM }}</p>
                                <p>性别：{{ ssdlr.XB }}</p>
                                <p>民族：{{ ssdlr.MZ }}</p>
                              <!--  <p>出生日期：{{ ssdlr.CSRQ.year+'年'+ssdlr.CSRQ.month+'月'+ssdlr.CSRQ.day+'日' }}</p>
                              -->
                                <p>出生日期：{{ ssdlr.CSRQ }}</p>
                                <p>身份证号码：{{ ssdlr.ZJHM }}</p>
                                <p>联系电话：{{ ssdlr.DH }}</p>
                                <p>住址：{{ ssdlr.DZ }}</p>
                            </div>
                        </el-card>
                    </template>
                </el-table-column>


            </el-table>


            <el-row :gutter="20">
                <el-col>
                    <el-button style="width: 100%" type="primary" @click="next()">下一步</el-button>
                </el-col>
            </el-row>
        </el-form>

        <el-dialog width="100%" title="填写诉讼代理人" v-if="dialogFormVisible" :visible.sync="dialogFormVisible">
            <SSDLR v-model="this.SSDLRForm" ref="ssdlrForm" :tid="this.ssdlrFormRef" @updatessldr="updateSSDLR"></SSDLR>
            <div slot="footer" class="dialog-footer">
                <el-row :gutter="5">
                    <el-col :span="12">
                        <el-button style="width: 100%" @click="dialogFormCancel">取 消</el-button>
                    </el-col>
                    <el-col :span="12">
                        <el-button style="width: 100%" type="primary" @click="dialogFormSubmit">确 定</el-button>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>


    </div>

</template>

<script>
    import {mapActions, mapState} from "vuex";

    import BirthdayPicker from "@/components/Form/BirthdayPicker";

    import copy from 'fast-copy';
    import MZ from '@/components/Form/MZ';
    import SSDLR from "@/components/Form/SSDLR";
    import IDValidator from 'id-validator';
    import moment from 'moment';
    import dw from "@/utils/trial"

    export default {
        name: "Dsr",

        components: {
            SSDLR,
            BirthdayPicker,
            MZ

        },

        data() {

            let idValidator = new IDValidator();

            let XMValidator = (rule, value, callback) => {

                if (value === undefined) {

                    if (!rule.field || rule.field === '') {
                        return callback(new Error('姓名不能为空'))
                    }
                } else if (!value || value === '') {
                    return callback(new Error('姓名不能为空'))
                }

                callback();
            }

            let ZJHMValidator = (rule, value, callback) => {

                if (!value || value === '') {
                    return callback(new Error('身份证号码不能为空'))
                }
                if (!idValidator.isValid(value)) {
                    return callback(new Error('身份证号码不正确'))
                }
                callback();
            }

            let CSRQValidator = (rule, value, callback) => {

                // if (value.year === "" || value.month === "" || value.day === "") {
                //     return callback(new Error('请填写出生日期'))
                // }
                if (!value || value === "") {
                    return callback(new Error('请填写出生日期'))
                }
                callback();
            }

            return {
                dialogFormVisible: false,


                ssdlrFormRef: 'ssdlr1',
                formRef: 'f1',
                formData: {
                    dsr: [],
                    trial_extra_type: ""
                },

                SSDLRForm: {
                    type: "1",
                    XM: "",
                    DZ: "",
                    SWS: "",
                    XB: "",
                    CSRQ:"",
                    // CSRQ: {
                    //     year: "",
                    //     month: "",
                    //     day: "",
                    // },
                    DH: "",
                    MZ: "",
                    trial_dsr_id: "",
                    index: ""
                },


                rules: {
                    XM: [
                        {required: true, validator: XMValidator, trigger: 'blur'}
                    ],
                    ZJHM: [
                        {required: true, validator: ZJHMValidator, trigger: 'blur'}
                    ],
                    XB: {required: true, message: "性别不能为空", trigger: 'blur'},
                    MZ: {required: true, message: "民族不能为空", trigger: 'blur'},
                    CSRQ: {required: true, validator: CSRQValidator, trigger: 'blur'},
                    DH: {
                        required: true, validator: (rules, value, callback) => {

                            if (value && value.length === 0) {
                                return callback(new Error('电话不能为空'))
                            }
                            callback();
                        }, trigger: 'focus'
                    },

                    DZ: {
                        required: true, validator: (rules, value, callback) => {

                            if (value && value.length === 0) {
                                return callback(new Error('住址不能为空'))
                            }
                            callback()
                        }, trigger: 'focus'
                    },

                    trial_extra_type: {
                        required: true, trigger: 'blur', message: '请选择保全类型'
                    }
                }
            }
        },

        watch: {

            AH(nv) {
                if (nv !== "") {
                    this.getInfo();
                }
            }
        },

        created() {

            // if (this.AH !== "") {
            //     this.getInfo();
            // }
        },

        computed: {

            ...mapState([
                'AH', 'step', 'submitData',
            ]),

            getDHValidator(){
                return function(row){
                    if( row.DW.indexOf( '原告') < 0 ){
                        //被告
                        return {validator:(rules,value,callback)=>{callback();},trigger:'focus'};
                    }else{
                        //原告
                        return {required:true,validator:(rules,value,callback)=>{

                                if (value && value.length === 0) {
                                    return callback(new Error('电话不能为空'))
                                }
                                callback();
                            },trigger:'focus'}
                    }
                }
            }
        },

        methods: {
            onTrialExtraTypeChange(v) {

                this.$emit('trialextratypechange', v);
            },

            getInitSSDLR() {
                return {
                    type: "1",
                    XM: "",
                    DZ: "",
                    SWS: "",
                    XB: "",
                    // CSRQ: {
                    //     year: "",
                    //     month: "",
                    //     day: "",
                    // },
                    CSRQ:"",
                    DH: "",
                    MZ: "",
                    trial_dsr_id: "",
                    index: ""
                }
            },
            ...mapActions([
                'setStep', 'setSubmitData', 'setBgList', 'setYgList'
            ]),


            onBirthdayChange(v, row) {
                this.$refs[this.formRef].validateField('dsr.' + row.$index + '.CSRQ')
            },

            parse(row) {

                let validator = new IDValidator();
                if (validator.isValid(row.ZJHM)) {
                    return validator.getInfo(row.ZJHM);
                }
                return false;
            },

            //解析证件号码
            parseZJHM(row) {


                let info = this.parse(row);

                if (info) {
                    this.resetFormData((v, i) => {
                        if (v.trial_dsr_id === row.trial_dsr_id) {
                            if (info.sex === 1) {
                                v.XB = '男';
                            } else {
                                v.XB = '女';
                            }
                            let birth = moment(info.birth)
                            v.CSRQ = birth.format('YYYY-MM-DD')
                            // v.CSRQ = {
                            //     "year": birth.year(),
                            //     "month": birth.month() + 1,
                            //     "day": birth.date()
                            // }
                        }
                    })
                }

            },

            handleDHDel(tag, row, scope) {

                this.resetFormData((v, i) => {
                    if (row.trial_dsr_id === v.trial_dsr_id) {
                        v.DH = v.DH.filter((vv, ii) => {
                            return (vv.content !== tag.content)
                        })
                    }

                });

                this.$refs[this.formRef].validateField('dsr.' + scope.index + '.DH')

            },


            handleDZDel(tag, row, scope) {

                this.resetFormData((v, i) => {
                    if (row.trial_dsr_id === v.trial_dsr_id) {
                        v.DZ = v.DZ.filter((vv, ii) => {
                            return (vv.content !== tag.content)
                        })
                    }

                })
                this.$refs[this.formRef].validateField('dsr.' + scope.index + '.DZ')
            },


            removeSSDLR(row, index) {
                this.resetFormData((v, i) => {
                    if (row.trial_dsr_id === v.trial_dsr_id) {
                        v.SSDLR = v.SSDLR.filter((vv, ii) => {
                            return (ii !== index);
                        })
                    }
                })
            },

            editSSDLR(ssdlr, row, index) {

                this.SSDLRForm = Object.assign(this.SSDLRForm, ssdlr);
                this.SSDLRForm.trial_dsr_id = row.trial_dsr_id;
                this.SSDLRForm.index = index;
                this.dialogFormVisible = true;
            },

            dialogFormCancel() {
                this.dialogFormVisible = false;
                this.SSDLRForm = this.getInitSSDLR();
            },

            dialogFormSubmit() {

                this.$refs['ssdlrForm'].validateForm()
                    .then((res) => {

                        this.dialogFormVisible = false;

                        let newData = copy(this.SSDLRForm)

                        this.resetFormData((v, i) => {

                            if (v.trial_dsr_id === newData.trial_dsr_id) {

                                if (newData.index !== "") {
                                    //修改

                                    delete newData.trial_dsr_id;
                                    v.SSDLR[newData.index] = newData;
                                    delete newData.index;

                                } else {
                                    //新增
                                    delete newData.index;
                                    delete newData.trial_dsr_id;
                                    v.SSDLR.push(newData)
                                }
                            }
                        });

                    })


            },

            handleDHEdit(tag, row) {


            },

            handleDZEdit(tag, row) {


            },


            onAddSSDLR(row) {

                this.SSDLRForm = this.getInitSSDLR();
                this.SSDLRForm.trial_dsr_id = row.trial_dsr_id;
                this.dialogFormVisible = true;
            },


            handleDZInput(row, scope) {
                row.input_DZ = row.input_DZ.trim();

                if (row.input_DZ === "") {
                    row.is_input_DZ = false;
                    return;
                }
                let i = row.DZ.findIndex((v, i) => {
                    return (v.content === row.input_DZ);
                })
                if (i > -1) {
                    return;
                }
                this.resetFormData((v, i) => {
                    if (v.trial_dsr_id === row.trial_dsr_id) {
                        v.DZ.push({content: row.input_DZ, type: 2,})
                        v.is_input_DZ = false;
                        v.input_DZ = "";
                    }
                });
                this.$refs[this.formRef].clearValidate(`dsr.` + scope.$index + `.DZ`);
            },


            handleDHInput(row, scope) {


                row.input_DH = row.input_DH.trim();


                if (row.input_DH === "") {
                    row.is_input_DH = false;

                    return;
                }
                let i = row.DH.findIndex((v, i) => {
                    return (v.content === row.input_DH);
                })
                if (i > -1) {
                    return;
                }
                this.resetFormData((v, i) => {
                    if (v.trial_dsr_id === row.trial_dsr_id) {
                        v.DH.push({content: row.input_DH, type: 1})
                        v.is_input_DH = false;
                        v.input_DH = "";
                    }
                });
                this.$refs[this.formRef].clearValidate(`dsr.` + scope.$index + `.DH`);
            },


            resetFormData(callback, options = {}) {
                let newData = copy(this.formData);

                if (options.before) {
                    options.before(newData)
                }
                newData.dsr.forEach(callback)

                if (options.after) {
                    options.after(newData)
                }
                this.formData = newData;
            },


            showDHInput(row, ref) {

                this.resetFormData((v, i) => {
                    if (v.trial_dsr_id === row.trial_dsr_id) {
                        v.is_input_DH = true;
                    }
                });
                this.$nextTick(() => {
                    this.$refs[ref].focus();
                })
            },

            showDZInput(row, ref) {

                this.resetFormData((v, i) => {
                    if (v.trial_dsr_id === row.trial_dsr_id) {
                        v.is_input_DZ = true;
                    }
                });
                this.$nextTick(() => {
                    this.$refs[ref].focus();
                })
            },

            getInfo() {

                let params = {
                    AH: this.AH,
                    //trial_extra_id:this.trialExtraId
                };
                this.$api.getCasesInfo(params)
                    .then(res => {
                        res.data.dsr.map(v => {
                            v.is_input_DH = false;
                            v.input_DH = "";
                            v.is_input_DZ = false;
                            v.input_DZ = "";
                            let info = this.parse(v)
                            if (info) {
                                v.XB = info.sex === 1 ? '男' : '女';
                                let birth = moment(info.birth)
                                v.CSRQ = birth.format('YYYY-MM-DD')
                                // v.CSRQ = {
                                //     "year": birth.year(),
                                //     "month": birth.month() + 1,
                                //     "day": birth.date()
                                // }
                            }
                        })
                        this.formData.dsr = res.data.dsr;
                        this.formData.trial_extra_type = res.data.trial_extra_type
                    }).catch(err => {

                })

            },

            updateSSDLR(v) {

                //  console.log(v);
                this.SSDLRForm = v;
            },


            next() {

                this.$refs[this.formRef].validate()
                    .then((res) => {

                        let sd = this.submitData;

                        sd.dsr = copy(this.formData.dsr);
                        sd.trial_extra_type = this.formData.trial_extra_type;


                        let ygList = [];
                        let bgList = [];
                        if (sd.dsr) {
                            sd.dsr.map((v, i) => {
                                if (dw.ygdw.includes(v.DW)) {
                                    //原告
                                    ygList.push({value: v.XM, label: v.XM})
                                } else {
                                    bgList.push({value: v.XM, label: v.XM})
                                }
                            });
                        }

                        this.setSubmitData(sd);

                        this.setYgList(ygList);

                        this.setBgList(bgList);

                        this.setStep(this.step + 1);
                    }).catch(err=>{
                        if (false === err) {
                            this.$message({
                                type: 'warning',
                                message:'请完善表单资料'
                            })
                        }
                    });


            }
        }

    }
</script>


<style scoped>

    .mb2 {
        margin-bottom: 2rem;
    }

    .text {
        font-size: 14px;
    }

    .item {
        margin-bottom: 18px;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }

    .clearfix:after {
        clear: both
    }

    .box-card {
        width: 100%;
    }
</style>